package com.avalonsql.core.configs;

import org.apache.log4j.Logger;

import javax.swing.*;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.net.URL;

public class IconsConfig extends Config {

    protected static IconsConfig instance = null;
    private static Logger logger = Logger.getLogger(IconsConfig.class);

    protected IconsConfig() {
        super();
    }

    public static IconsConfig getInstance() throws ConfigIOException {
        if (instance == null) {
            instance = new IconsConfig();
            instance.reload();
        }
        return instance;
    }


    public Config reload() throws ConfigIOException {
        FileInputStream fileInputStream = null;
        try {
            fileInputStream = new FileInputStream(getPropertiesFile());
            properties.load(fileInputStream);
            changed = false;
        } catch (FileNotFoundException e) {
            throw new ConfigIOException(e);
        } catch (IOException e) {
            throw new ConfigIOException(e);
        } finally {
            try {
                fileInputStream.close();
            } catch (IOException e) {
                throw new ConfigIOException(e);
            }
        }

        return this;
    }

    @Override
    public String getPropertiesFile() {
        return Const.DEFAULT_ICONS_CONFIG;
    }

    public Icon getIcon(String name) {
        String property = getProperty(name);
        if (property == null) {
            property = getProperty("default");
        }
        if (property != null) {
            URL location = getClass().getResource(property);
            if (location != null) {
                return new ImageIcon(location);
            } else {
                logger.warn("Resource path " + property + " for property " + name + " not found!");
            }
        }
        return null;
    }

}
